<template>
	<view class="content">
		<view
			v-if="bindStatus && login.log_on_way === 0"
			class="uni-color-main text-w"
			style="position: fixed; top: calc(44px + 32rpx)"
			@click="switchLogin"
		>
			返回登录
		</view>
		<view v-if="bindStatus" class="welcome-login">欢迎{{ login.log_on_way ? '登录' : '注册' }}</view>
		<view v-else class="welcome-login">绑定手机号</view>
		<view v-if="login.log_on_way && bindStatus" class="uni-mt-8">
			<text class="uni-color-grey">还没有账号，</text>
			<text class="uni-color-main" @click="registerNow">立即注册</text>
		</view>
		<view class="flex_sbc input-box uni-mt-80 uni-px-24 uni-F5F5F5-bg">
			<view class="flex_fsc">
				<image
					:src="setting.oss_pub_domain + '/app-img/login/icon_user.png'"
					class="icon-size uni-mr-24"
				></image>
				<input
					type="number"
					v-model="login.mobile"
					placeholder="请输入手机号码"
					placeholder-class="uni-placeholder"
					maxlength="11"
					@input="inputChange"
				/>
			</view>
			<image
				v-if="login.mobile"
				:src="setting.oss_pub_domain + '/app-img/login/icon_Shut.png'"
				class="icon-size"
				@click="clearMobile"
			></image>
		</view>
		<view v-if="login.log_on_way === 0" class="flex_sbc input-box uni-mt-32 uni-px-24 uni-F5F5F5-bg">
			<view class="flex_fsc">
				<image
					:src="setting.oss_pub_domain + '/app-img/login/icon_user.png'"
					class="icon-size uni-mr-24"
				></image>
				<input
					v-model="login.nickname"
					placeholder="请输入昵称"
					placeholder-class="uni-placeholder"
					maxlength="15"
					@input="inputChange"
				/>
			</view>
		</view>
		<view v-if="login.log_on_way != 1" class="flex_sbc input-box uni-mt-32 uni-px-24 uni-F5F5F5-bg">
			<view class="flex_fsc">
				<image
					:src="setting.oss_pub_domain + '/app-img/login/icon_mobile_code.png'"
					class="icon-size uni-mr-24"
				></image>
				<input
					type="number"
					v-model="login.mobile_code"
					placeholder="请输入验证码"
					placeholder-class="uni-placeholder"
					maxlength="6"
					@input="inputChange"
				/>
			</view>
			<view class="uni-color-main flex_sh" @click="getMobileCode">
				{{ codeSetting.state ? `${codeSetting.countdown}秒` : codeSetting.frist ? '获取验证码' : '重新获取' }}
			</view>
		</view>
		<view v-if="login.log_on_way != 2" class="flex_sbc input-box uni-mt-32 uni-px-24 uni-F5F5F5-bg">
			<view class="flex_fsc">
				<image
					:src="setting.oss_pub_domain + '/app-img/login/icon_password.png'"
					class="icon-size uni-mr-24"
				></image>
				<input
					:type="login.pass_type ? 'text' : 'password'"
					v-model="login.password"
					placeholder="请输入密码"
					placeholder-class="uni-placeholder"
					maxlength="11"
					@input="inputChange"
				/>
			</view>
			<image
				:src="`/static/login/icon${login.pass_type ? '' : '_no'}_visible.png`"
				class="icon-size"
				@click="login.pass_type = login.pass_type ? 0 : 1"
			></image>
		</view>
		<view
			class="input-box login-button"
			:class="[login.button_state ? 'uni-white uni-color-main-bg' : 'uni-color-grey uni-F5F5F5-bg']"
			@click="buttonFun"
		>
			{{ login.log_on_way ? (bindStatus ? '登录' : '绑定') : '注册' }}
		</view>
		<view
			v-if="bindStatus"
			class="uni-color-main text-w uni-mt-40 text-c"
			style="z-index: 999"
			@click="switchLogin"
		>
			{{ loginText[login.log_on_way] }}
		</view>
	</view>
	<view v-if="!keyboard" class="third-party-login z-font-24">
		<!-- #ifdef APP-PLUS -->
        <view v-if="login.log_on_way && bindStatus &&  osName == 'android'">
			<view class="uni-color-grey">第三方账号快速登录</view>
			<view class="flex_cc">
				<image
					:src="setting.oss_pub_domain + '/app-img/icon/WeChat.png'"
					class="wechat-icon uni-mt-60"
					@click="wxLoginCheck"
				></image>
				<!-- <image
					v-if="osName === 'ios'"
					:src="setting.oss_pub_domain + '/app-img/icon/apple.png'"
					class="wechat-icon uni-mt-60 uni-ml-32"
					@click="appleLoginCheck"
				></image> -->
			</view>
		</view>
		<!-- #endif -->
		<view class="flex_cc user-agreement-box" @click="login.agree = !login.agree">
			<image
				:src="`${setting.oss_pub_domain}/app-img/icon/student_select${login.agree ? 'ed' : ''}.png`"
				class="icon-size-32 uni-mr-16"
			></image>
			<view class="uni-color-grey">{{ login.log_on_way ? '登录' : '注册' }}即表示同意降杆APP</view>
			<view class="user-agreement" @click.stop="toWeb('https://www.jgtygolf.com/archives/66')">《用户协议》</view>
			<view>和</view>
			<view class="user-agreement" @click.stop="toWeb('https://www.jgtygolf.com/archives/64')">《隐私协议》</view>
		</view>
	</view>
	<uni-popup type="center" ref="agreePopup">
		<div class="popup">
			<div class="title">用户协议及隐私协议</div>
			<div class="uni-mt-16" style="line-height: 40rpx">
				<span>已阅读并同意</span>
				<span class="user-agreement" @click.stop="toWeb('https://www.jgtygolf.com/archives/66')">
					《用户协议》
				</span>
				<span>和</span>
				<span class="user-agreement" @click.stop="toWeb('https://www.jgtygolf.com/archives/64')">
					《隐私协议》
				</span>
			</div>
			<div class="confirm" @click="logInType === 1 ? wxLogin() : logInType === 2 ? appleLoginFun() : loginFuns()">同意并登录</div>
			<div
				class="uni-585C66 text-c uni-mt-32"
				@click="
					agreePopup.close();
					login.agree = false;
				"
			>
				不同意
			</div>
		</div>
	</uni-popup>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onBeforeUnmount } from 'vue';
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app';
import uniIm from '@/uni_modules/uni-im/lib/main.js';
import mixin from '@/uni_modules/uni-id-pages/common/login-page.mixin.js';
import { loginFun, getPhoneCode, register, wxLoginFun, appleLogin, bindPhone } from '@/api/login.js';
import { getUserInfo } from '@/api/user.js';
// import { updatePushId } from '@/api/my.js'
import getConfig from '@/utils/getConfig';
const uniIdCo = uniCloud.importObject('uni-id-co', {
	errorOptions: {
		type: 'toast'
	}
});
const { osName } = uni.getSystemInfoSync();
const { proxy: that } = getCurrentInstance();
const login = reactive({
	mobile: '',
	password: '',
	mobile_code: '',
	pass_type: 0,
	// 0 注册 1 密码登录 2 验证码登录
	log_on_way: 2,
	button_state: 0
});
inputChange();
const loginText = ['登录已有账号', '验证码登录', '密码登录'];

function reset() {
	login.password = '';
	login.mobile_code = '';
}

function registerNow() {
	reset();
	inputChange();
	login.log_on_way = 0;
}

function switchLogin() {
	login.log_on_way = login.log_on_way === 1 ? 2 : 1;
	reset();
	inputChange();
}

function clearMobile() {
	login.mobile = '';
	inputChange();
}

function inputChange() {
	if (login.log_on_way === 1) {
		login.button_state = login.mobile.toString().length === 11 && login.password ? 1 : 0;
	} else if (login.log_on_way === 2) {
		login.button_state = login.mobile.toString().length === 11 && login.mobile_code.toString().length === 6 ? 1 : 0;
	} else {
		login.button_state =
			login.mobile.toString().length === 11 &&
			login.password &&
			login.mobile_code.toString().length === 6 &&
			login.nickname
				? 1
				: 0;
	}
}

const codeSetting = reactive({
	countdown: 30,
	frist: 1,
	state: 0,
	interval: ''
});

function getMobileCode() {
	if (codeSetting.state) return;
	if (login.mobile.toString().length != 11) return that.tools.alert('手机号格式错误');
	getPhoneCode({
		phone: login.mobile
	}).then((res) => {
		codeSetting.state = 1;
		codeSetting.frist = 0;
		codeSetting.interval = setInterval(() => {
			codeSetting.countdown--;
			if (codeSetting.countdown <= 0) {
				clearInterval(codeSetting.interval);
				codeSetting.countdown = 30;
				codeSetting.state = 0;
			}
		}, 1000);
	});
}
onBeforeUnmount(() => {
	clearInterval(codeSetting.interval);
});

function loginFuns() {
	if (!login.button_state) return;
	agreePopup.value.close();
	if (login.log_on_way === 1) {
		// 密码登录
		loginFun({
			username: login.mobile,
			password: login.password,
			type: 2
		}).then((res) => {
			that.tools.alert('登录成功');
			loginSuccess(res);
		});
	} else if (login.log_on_way === 2) {
		if (bindStatus.value) {
			// 验证码登录
			loginFun({
				username: login.mobile,
				code: login.mobile_code,
				type: 2
			}).then((res) => {
				that.tools.alert('登录成功');
				loginSuccess(res);
			});
		} else {
			// 微信绑定手机号
			bindPhone(
				{
					code: login.mobile_code,
					username: login.mobile
				},
				temporarilyToken.value
			).then((res) => {
				that.tools.alert('绑定完成');
				loginSuccess({
					token: temporarilyToken.value
				});
			});
		}
	} else {
		// 注册
		register({
			username: login.mobile,
			code: login.mobile_code,
			password: login.password,
			nickname: login.nickname,
			type: 2
		}).then((res) => {
			that.tools.alert('注册成功');
			loginSuccess(res);
		});
	}
}

const agreePopup = ref(),
	logInType = ref(0); // 0 验证码或密码 1 微信 2 苹果
function buttonFun() {
	if (!login.button_state) return;
	if (!login.agree) {
		logInType.value = 0;
		agreePopup.value.open();
	} else loginFuns();
}

let onBack = 0;
onLoad((opt) => {
	onBack = parseInt(opt.back || 0);
});
async function loginSuccess(res) {
	uni.setStorageSync('token', res.token);
	const info = await getUserInfo();
	Object.assign(that.userInfo, info);
	// updatePushId()
	const uinRes=await	uniIdCo.login({
			captcha: '',
			password: info.userId + '_grf_0920',
			username: 'grf_user_' + info.userId
		});
		
		console.log("登陆成功",uinRes)
		
		if(uinRes){
			mixin.methods.loginSuccess(uinRes);
		}else{
			console.log("登陆失败")
		}
		// .then((e) => {
		// 	// console.log(e)
		// 	mixin.methods.loginSuccess(e);
		// })
		// .catch((e) => {
		// 	console.log(e, 'erro');
		// 	if (e.errCode == 'uni-id-captcha-required') {
		// 		console.log('needCaptcha = true');
		// 		// that.needCaptcha = true
		// 	} else if (mixin.needCaptcha) {
		// 		console.log('登录失败，自动重新获取验证码');
		// 		// //登录失败，自动重新获取验证码
		// 		// that.$refs.captcha.getImageCaptcha()
		// 	}
		// });
	const userState = uni.getStorageSync('start-state');
	if (onBack) {
		uni.setStorageSync('new-user', res.newUser);
		uni.navigateBack();
	} else {
		uni.reLaunch({
			url: res.newUser && userState == 2 ? '/pages/student/guide/gender' : '/pages/tabbar-page/tabbar-0'
		});
	}
}

//  微信登录
function wxLoginCheck() {
	if (!login.agree) {
		logInType.value = 1;
		agreePopup.value.open();
	} else wxLogin();
}
function wxLogin() {
	agreePopup.value.close();
	uni.login({
		provider: 'weixin',
		onlyAuthorize: true, // 微信登录仅请求授权认证
		success: function (event) {
			const { code } = event;
			wxLoginFun({
				code
			}).then(res => {
				if (res.bindPhone) {
					that.tools.alert('登录成功');
					loginSuccess(res);
				} else {
					login.log_on_way = 2;
					bindStatus.value = 0;
					temporarilyToken.value = res.token;
				}
			});
		},
		fail: function (err) {
			that.tools.alert('授权失败');
		}
	});
}

//  微信登录后绑定手机号
const bindStatus = ref(1),
	temporarilyToken = ref('');

const keyboard = ref(false);
// #ifdef APP-PLUS
uni.onKeyboardHeightChange((res) => {
	keyboard.value = !!res.height;
});
// #endif

function toWeb(url) {
	uni.navigateTo({
		url: '/pages/index/my-webview?url=' + url
	});
}

// 苹果登录
function appleLoginCheck() {
	if (!login.agree) {
		logInType.value = 2;
		agreePopup.value.open();
	} else appleLoginFun();
}
function appleLoginFun() {
	agreePopup.value.close();
	uni.login({
	    provider: 'apple',
	    success: loginRes => {
	        // 登录成功
	        uni.getUserInfo({
	            provider: 'apple',
	            success: info => {
					appleLogin(info.userInfo).then(res => {
						if (res.bindPhone) {
							that.tools.alert('登录成功');
							loginSuccess(res);
						} else {
							login.log_on_way = 2;
							bindStatus.value = 0;
							temporarilyToken.value = res.token;
						}
					})
	            }
	        })
	    },
	    fail: err => {
	        this.tools.alert('登录失败')
	    }
	});
}

getConfig();
</script>

<style lang="scss">
@import './login.scss';
</style>
